﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Joy.Erp.BasicArchives.Production;
using Joy.Erp.Ufida.Core;
using Microsoft.Extensions.Logging;

namespace Joy.Erp.Ufida.Production
{
    public class ProductionOrderTypeSyncAppService : UfidaAppService, IProductionOrderTypeSyncAppService
    {
        protected IProductionOrderTypeRepository ProductionOrderTypeRepository => LazyServiceProvider.LazyGetRequiredService<IProductionOrderTypeRepository>();
        protected IMODocTypeUfidaAppService MODocTypeUfidaAppService => LazyServiceProvider.LazyGetRequiredService<IMODocTypeUfidaAppService>();

        public async Task<AnalysisDto> AnalyzeAsync()
        {
            var analysisDto = new AnalysisDto();
            analysisDto.Id = typeof(ProductionOrderType).FullName;

            // 获取U9数据的ID列表
            var u9list = await MODocTypeUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID.ToString()).ToHashSet();
            analysisDto.U9Count = u9Ids.Count;

            // 使用数据库查询优化，只查询需要的字段
            var pmcQuery = await ProductionOrderTypeRepository.GetQueryableAsync();

            // 获取PMC总数
            analysisDto.Count = await AsyncExecuter.CountAsync(pmcQuery.Where(x => !x.IsDeleted));

            // 获取已同步的SourceKey列表
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 快速计算已同步数量
            analysisDto.AsyncCount = syncedSourceKeys.Count(key => u9Ids.Contains(key));
            analysisDto.UnasyncCount = analysisDto.U9Count - analysisDto.AsyncCount;
            analysisDto.SelfCount = analysisDto.Count - analysisDto.AsyncCount;

            return analysisDto;
        }

        public async Task<List<long>> GetUnasyncIds()
        {
            // 获取U9的所有ID
            var u9list = await MODocTypeUfidaAppService.GetAllAsync();
            var u9Ids = u9list.Select(x => x.ID).ToList();

            // 使用数据库查询，只查询已同步的SourceKey
            var pmcQuery = await ProductionOrderTypeRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );

            // 使用 HashSet 优化查找性能，时间复杂度从 O(n²) 降到 O(n)
            var syncedSourceKeySet = new HashSet<string>(syncedSourceKeys);

            // 找出未同步的ID
            var unasyncIds = u9Ids
                .Where(id => !syncedSourceKeySet.Contains(id.ToString()))
                .ToList();

            return unasyncIds;
        }

        public async Task<int> CreateByIds‌Async(long[] ids)
        {
            if (ids == null || ids.Length == 0)
                return 0;

            var pmcQuery = await ProductionOrderTypeRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x =>
                        idStrings.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                    )
                    .Select(x => x.SourceKey)
            );
            var existingSet = new HashSet<string>(existingSourceKeys);

            // 过滤出需要创建的ID
            var needCreateIds = ids.Where(id => !existingSet.Contains(id.ToString())).ToList();
            if (needCreateIds.Count == 0)
                return ids.Length;

            Logger.LogInformation($"[批量同步-生产订单类型] 开始处理 {needCreateIds.Count} 条新增，总共 {ids.Length} 条（已存在 {existingSet.Count} 条）");

            var entities = new List<ProductionOrderType>();
            foreach (var id in needCreateIds)
            {
                try
                {
                    var dto = await MODocTypeUfidaAppService.GetAsync(id);
                    if (dto != null)
                    {
                        var entity = GetEntity(dto);
                        if (entity != null)
                        {
                            entities.Add(entity);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-生产订单类型] 获取U9数据失败，Id: {id}");
                }
            }

            var successCount = 0;
            if (entities.Count > 0)
            {
                using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
                {
                    try
                    {
                        await ProductionOrderTypeRepository.BulkInsertAsync(entities, autoSave: false);
                        await uow.CompleteAsync();
                        successCount = entities.Count;
                    }
                    catch (Exception ex)
                    {
                        Logger.LogWarning(ex, $"[批量同步-生产订单类型] 批量插入失败，{ex.Message}");
                    }
                }
            }

            Logger.LogInformation($"[批量同步-生产订单类型] 完成！成功创建 {successCount} 条，已存在 {existingSet.Count} 条，总计 {successCount + existingSet.Count} 条");

            return successCount + existingSet.Count;
        }

        public async Task<List<long>> GetSyncedIds()
        {
            var pmcQuery = await ProductionOrderTypeRepository.GetQueryableAsync();
            var syncedSourceKeys = await AsyncExecuter.ToListAsync(
                pmcQuery
                    .Where(x => !x.IsDeleted && x.SourceType == SourceConfig.SourceType)
                    .Select(x => x.SourceKey)
            );
            return syncedSourceKeys
                .Select(
                    key => long.TryParse(key, out var parsedId) ? (long?)parsedId : null
                )
                .Where(id => id.HasValue)
                .Select(id => id.Value)
                .ToList();
        }

        public async Task<int> UpdateByIdsAsync(long[] ids)
        {
            if (ids == null || ids.Length == 0) return 0;

            Logger.LogInformation($"[批量同步-生产订单类型] 开始处理 {ids.Length} 条更新");
            var pmcQuery = await ProductionOrderTypeRepository.GetQueryableAsync();
            var idStrings = ids.Select(id => id.ToString()).ToList();
            var existingEntities = await AsyncExecuter.ToListAsync(
                pmcQuery.Where(x =>
                    idStrings.Contains(x.SourceKey) && x.SourceType == SourceConfig.SourceType
                )
            );
            if (existingEntities.Count == 0)
            {
                Logger.LogWarning($"[批量同步-生产订单类型] 没有找到需要更新的记录");
                return 0;
            }
            var entityDict = existingEntities.ToDictionary(x => x.SourceKey, x => x);
            var allU9DataDict = new Dictionary<long, MODocTypeUfidaDto>();
            foreach (var id in ids)
            {
                try
                {
                    if (!entityDict.ContainsKey(id.ToString()))
                        continue;

                    var dto = await MODocTypeUfidaAppService.GetAsync(id);
                    if (dto != null)
                        allU9DataDict[id] = dto;
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-生产订单类型] 获取U9数据失败，Id: {id}");
                }
            }
            var entitiesToUpdate = new List<ProductionOrderType>();
            var entitiesToDelete = new List<ProductionOrderType>();
            foreach (var id in ids)
            {
                try
                {
                    var key = id.ToString();
                    if (!entityDict.TryGetValue(key, out var entity))
                        continue;

                    if (!allU9DataDict.TryGetValue(id, out var u9Data))
                    {
                        entitiesToDelete.Add(entity);
                        continue;
                    }

                    entity.Code = u9Data.Code;
                    entity.DisplayName = u9Data.Name;
                    entity.SourceCreatedOn = u9Data.CreatedOn;
                    entitiesToUpdate.Add(entity);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"[批量同步-生产订单类型] 修改实体失败，Id: {id}");
                }
            }
            if (entitiesToUpdate.Count == 0 && entitiesToDelete.Count == 0)
            {
                Logger.LogInformation($"[批量同步-生产订单类型] 无需更新或删除记录");
                return 0;
            }

            var updateCount = 0;
            var deleteCount = 0;
            using (var uow = UnitOfWorkManager.Begin(new Volo.Abp.Uow.AbpUnitOfWorkOptions(), requiresNew: true))
            {
                try
                {
                    if (entitiesToUpdate.Count > 0)
                    {
                        await ProductionOrderTypeRepository.BulkUpdateAsync(
                            entitiesToUpdate,
                            autoSave: false
                        );
                        updateCount = entitiesToUpdate.Count;
                    }

                    if (entitiesToDelete.Count > 0)
                    {
                        await ProductionOrderTypeRepository.BulkDeleteAsync(
                            entitiesToDelete,
                            autoSave: false
                        );
                        deleteCount = entitiesToDelete.Count;
                    }

                    await uow.CompleteAsync();
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(
                        ex,
                        $"[批量同步-生产订单类型] 批量更新/删除失败，{ex.Message}"
                    );
                }
            }

            Logger.LogInformation($"[批量同步-生产订单类型] 完成！成功更新 {updateCount} 条，删除 {deleteCount} 条");
            return updateCount + deleteCount;
        }

        private ProductionOrderType GetEntity(MODocTypeUfidaDto moDocTypeUfidaDto)
        {
            var entity = new ProductionOrderType
            {
                SourceType = SourceConfig.SourceType,
                SourceKey = moDocTypeUfidaDto.ID.ToString(),
                SourceCreatedOn = moDocTypeUfidaDto.CreatedOn,
                Code = moDocTypeUfidaDto.Code,
                DisplayName = moDocTypeUfidaDto.Name,
                CreationTime = Clock.Now,
                CreatorId = CurrentUser.Id,
                TenantId = CurrentTenant.Id,
            };

            entity.SetId(GuidGenerator.Create());
            return entity;
        }
    }
}
